package com.htn.auth.controller;

import javax.servlet.http.HttpServletRequest;



import cn.hutool.json.JSONObject;
import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import com.htn.auth.form.OneClickLoginType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.htn.auth.form.LoginRequestVO;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.domain.WxLoginVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.htn.auth.form.LoginBody;
import com.htn.auth.form.RegisterBody;
import com.htn.auth.service.SysLoginService;
import com.htn.common.core.domain.R;
import com.htn.common.core.utils.StringUtils;
import com.htn.common.security.service.TokenService;
import com.htn.system.api.model.LoginUser;

/**
 * token 控制
 * 
 * @author htn
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    public static final String AccessKeyID = "LTAI5t9u19GEManwRrXQyE1R";

    public static final String AccessKeySecret = "FKwmjJCo2zdTJueFMmkAgpuijgRkpd";


    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dypnsapi.aliyuncs.com";
        return new Client(config);
    }


    @ApiOperation(value = "一键登录", notes = "一键登录", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "App端SDK获取的登录token",name = "accessToken",dataType = "String"),
            @ApiImplicitParam(value = "类型 DRIVER FOREMAN",name = "type",dataType = "String")
    })
    @PostMapping("getMobileByAndroid")
    public DataResponse getMobileByAndroid(String accessToken,String type) throws Exception {
        Client client = TokenController.createClient(AccessKeyID, AccessKeySecret);
        GetMobileRequest getMobileRequest = new GetMobileRequest().setAccessToken(accessToken);
        // 复制代码运行请自行打印 API 的返回值
        GetMobileResponse mobile = client.getMobile(getMobileRequest);
        LoginRequestVO loginRequestVO =new LoginRequestVO();
        String msg = mobile.getBody().getMessage();
        if(msg.equals("OK")){
            loginRequestVO.setUsername( mobile.getBody().getGetMobileResultDTO().getMobile());
            loginRequestVO.setType(type);
            loginRequestVO.setFlag(OneClickLoginType.ONE.getValue());
            DataResponse login = this.commonLogin(loginRequestVO);
            return login;
        }else {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"手机号获取失败，请重新登录");
        }
    }

    @PostMapping("syslogin")
    public R<?> login(@RequestBody LoginBody form){
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("login")
    public DataResponse commonLogin( LoginRequestVO loginRequestVO){

        return sysLoginService.commonLogin(loginRequestVO);
    }

    @PostMapping("wxCode")
    public DataResponse wxCode(@RequestBody WxLoginVO wxLoginVO){

        return sysLoginService.wxCode(wxLoginVO);
    }



    @PostMapping("wxLogin")
    public DataResponse wxLogin(@RequestBody WxLoginVO wxLoginVO){

        return sysLoginService.wxLogin(wxLoginVO);
    }

    @DeleteMapping("logout")
    public DataResponse logout(HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody){
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
